<template>
  <div>
    <el-form ref="assetForm" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-row :gutter="40">
        <el-col v-if="id !== -1" :span="8">
          <el-form-item label="编码">
            <el-input v-model="formItem.code" placeholder="编码" disabled />
          </el-form-item>
        </el-col>
        <el-col v-if="id !== -1" :span="8">
          <el-form-item label="状态">
            <el-select v-model="formItem.changeStatus" class="select_input" disabled placeholder="请选择维保变更状态">
              <el-option v-for="(item) in status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="id!='-1'" :span="8">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="formItem.createTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col v-if="id!='-1'" :span="8">
          <el-form-item label="更新时间">
            <el-date-picker
              v-model="formItem.updateTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商">
            <el-input v-model="formItem.manufacturerName" placeholder="请选择供应商" @focus="handleIconClick" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商联系人">
            <el-input v-model="formItem.manufacturerPerson" placeholder="供应商联系人" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商联系电话">
            <el-input v-model="formItem.manufacturerPhone" placeholder="供应商联系电话" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维保开始时间">
            <el-date-picker
              v-model="formItem.maintenanceStart"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维保结束时间">
            <el-date-picker
              v-model="formItem.maintenanceEnd"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维保负责人">
            <el-input v-model="formItem.maintenanceUserName" placeholder="请输入维保负责人" @focus="handleMaintenanceIconClick" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维保说明">
            <el-input v-model="formItem.maintenanceNote" placeholder="请输入维保说明" :maxlength="1023" type="textarea" :rows="2" :autosize="true" resize="none" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-col :span="24">
      <div class="form-info-title">
        <i class="el-icon-document" /><span>变更资产</span>
        <div>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleSelectAssets">选择资产</el-button>
          <el-button type="primary" size="mini" icon="el-icon-delete" @click="handleRemove">移除</el-button>
        </div>
      </div>
    </el-col>
    <!-- <el-table :data="formItem.assets" height="500" style="width: 100%" @select="tableSelection">
      <el-table-column type="selection" width="55" />
      <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable" />
    </el-table> -->
    <PageableTable
      :loading="false"
      :data="formItem.assets"
      :table-height="500"
      :disable-pageable="true"
      :multiple-selected="true"
      class="fixed-table-table"
      @selection-change="tableSelection"
    >
      <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
        <template slot-scope="scope">
          <column-render :render="column.render" :row="scope.row" :column="column" />
        </template>
      </el-table-column>
    </PageableTable>

    <SelectDialog title="选择供应商" :append-to-body="true" :show="manucacturerSelect" @on-ok="selectManufaturerOk" @on-cancel="selectManufaturerCancel">
      <manufacturer ref="manfacturer" :status="true" :for-selection="true" :multiple-selected="true" /></SelectDialog>
    <SelectDialog title="选择维保负责人" :append-to-body="true" :show="mainteanceSelDialogFormVisible" @on-ok="selectMainteanceOk" @on-cancel="selectMainteanceCancel">
      <UsersPage ref="usersMainteance" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
    <SelectDialog title="选择资产" :append-to-body="true" :show="assetSelDialogFormVisible" @on-ok="selectAssetOk" @on-cancel="selectAssetCancel">
      <assets ref="assets" :for-selection="true" />
    </SelectDialog>
  </div>
</template>

<script>
import { findByDictionaryType } from '@neu/dcam-ui/api/dictionary'
import UsersPage from '@neu/auth-ui/views/users/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import { create, update, detail } from '@neu/dcam-ui/api/maintenanceChange'
import manufacturer from '@neu/dcam-ui/views/manufacturer/tables'
import assets from '@neu/dcam-ui/views/fixedAsset/tables'
import { formatDate } from '@neu/biz-core/utils/utils'
import PageableTable from '@neu/biz-core/components/PageableTable'
// 定义一个表单原始项
const formItem = {
  code: '',
  changeStatus: '',
  maintenanceChangeDate: '',
  manufacturerId: '',
  manufacturerName: '',
  manufacturerPerson: '',
  manufacturerPhone: '',
  maintenanceId: '',
  maintenanceStart: null,
  maintenanceEnd: null,
  maintenanceUserId: '',
  maintenanceUserName: '',
  maintenanceNote: '',
  assets: []
}
export default {
  name: 'PermissionsEditForm',
  components: {
    manufacturer,
    UsersPage,
    SelectDialog,
    assets,
    PageableTable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },

  data() {
    return {
      /** 资产来源 */
      assetSource: [],
      /** 资产状态 */
      assetStatus: [],
      status: [{ value: 'created', label: '已创建' }, { value: 'confirmed', label: '已确认' }, { value: 'finish', label: '已完成' }],
      /** 要移除的资产 */
      removeData: [],
      /** 是否显示资产 */
      assetSelDialogFormVisible: false,
      /** 是否显示维保负责人的数据 */
      mainteanceSelDialogFormVisible: false,
      /** 供应商信息对话框是否显示 */
      manucacturerSelect: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        // manufacturerName: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
        // sequence: [{ required: true, message: '序列号不能为空', trigger: 'blur' }],
        // code: [{ required: true, message: '标识不能为空', trigger: 'blur' }],
        // assetTypeCode: [{ required: true, message: '选择类型', trigger: 'change' }],
        // createTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        // updateTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }]
      },
      insideColumns: [
        { title: '资产分类', width: 100, key: 'TypeName', display: true, fixed: true, render: (h, params) => {
          return h('span', params.row.assetTypeName)
        } },
        { title: '资产编号', width: 220, key: 'code', display: true, fixed: true },
        { title: '资产名称', width: 150, key: 'name', display: true, fixed: true },
        { title: '状态', width: 100, key: 'statusCode', display: true, fixed: true, render: (h, params) => {
          const status = this.assetStatus.filter(t => {
            return t.code === params.row.statusCode
          })
          const statusDesc = status.length === 1 ? status[0].text : params.row.statusCode
          return h('span', [
            h('el-tag', statusDesc)
          ])
        } },
        { title: '规格型号', width: 150, key: 'productName', display: true },
        { title: '放置位置', width: 100, key: 'locationName', display: true },
        { title: '使用部门', width: 100, key: 'orgName', display: true },
        { title: '使用人', width: 90, key: 'userName', display: true },
        { title: '计量单位', width: 80, key: 'measureUnit', display: true },
        { title: '单价', width: 70, key: 'money', display: true },
        { title: '使用期限（月）', width: 120, key: 'month', display: true },
        { title: '来源', width: 80, key: 'sourceCode', display: true, render: (h, params) => {
          const source = this.assetSource.filter(t => {
            return t.code === params.row.sourceCode
          })
          const sourceDesc = source.length === 1 ? source[0].text : params.row.sourceCode
          return h('span', [
            h('el-tag', sourceDesc)
          ])
        } },
        { title: '合同编号', width: 100, key: 'contractCode', display: true },
        { title: '合同名称', width: 100, key: 'contractName', display: true },
        { title: '供应商', width: 90, key: 'manufacturerName', display: true },
        { title: '供应商联系人', width: 130, key: 'manufacturerPerson', display: true },
        { title: '供应商联系方式', width: 140, key: 'manufacturerPhone', display: true },
        { title: '维保开始时间', width: 150, key: 'maintenanceStart', render: (h, params) => { return h('span', formatDate(params.row.maintenanceStart)) }, display: true },
        { title: '维保结束时间', width: 150, key: 'maintenanceEnd', render: (h, params) => { return h('span', formatDate(params.row.maintenanceEnd)) }, display: true },
        { title: '维保负责人', width: 120, key: 'maintenanceUserName', display: true },
        { title: '维保说明', width: 'auto', key: 'maintenanceNote', display: true },
        { title: '创建时间', width: 150, key: 'createTime', render: (h, params) => { return h('span', formatDate(params.row.createTime)) }, display: true },
        { title: '更新时间', width: 150, key: 'updateTime', render: (h, params) => { return h('span', formatDate(params.row.updateTime)) }, display: true }

      ]
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    findByDictionaryType('assetSource').then(res => {
      if (res.status === 'success') {
        this.assetSource = res.data
      }
    })
    findByDictionaryType('assetStatus').then(res => {
      if (res.status === 'success') {
        this.assetStatus = res.data
      }
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = { ... response.data }
          if (this.formItem.contract === null) {
            this.formItem.contract = {}
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.assetForm.validate((valid) => {
          if (valid) {
            if ((this.formItem.manufacturerId === '' || this.formItem.manufacturerId === null) && this.formItem.maintenanceStart === null && this.formItem.maintenanceEnd === null &&
            (this.formItem.maintenanceUserId === '' || this.formItem.maintenanceUserId === null) && (this.formItem.maintenanceNote === '' || this.formItem.maintenanceNote === null)) {
              return this.$message({
                showClose: true,
                message: '供应商、维保开始时间、维保结束时间、维保负责人、维保信息至少修改一项',
                type: 'error'
              })
            }
            if (this.formItem.assets.length === 0) {
              return this.$message({
                showClose: true,
                message: '至少选择一个资产',
                type: 'error'
              })
            }
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.assetForm.resetFields()
      formItem.assets = []
      this.formItem = { ...formItem }
    },
    /** 选择供货商 */
    handleIconClick() {
      this.manucacturerSelect = true
    },
    selectManufaturerCancel() {
      this.manucacturerSelect = false
    },
    selectManufaturerOk() {
      var manufacturers = this.$refs.manfacturer.selections
      if (manufacturers.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个供应商',
          type: 'error'
        })
      }
      if (manufacturers.length < 1) {
        this.formItem.manufacturerId = ''
        this.formItem.manufacturerName = ''
        this.formItem.manufacturerPerson = ''
        this.formItem.manufacturerPhone = ''
      } else {
        this.formItem.manufacturerId = manufacturers[0].id
        this.formItem.manufacturerName = manufacturers[0].name
        this.formItem.manufacturerPerson = manufacturers[0].person
        this.formItem.manufacturerPhone = manufacturers[0].phone
      }

      this.manucacturerSelect = false
    },
    /** 选择维保负责人 */
    handleMaintenanceIconClick() {
      this.mainteanceSelDialogFormVisible = true
    },
    selectMainteanceOk() {
      var mainteanceUsers = this.$refs.usersMainteance.selections
      if (mainteanceUsers.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个用户',
          type: 'error'
        })
      }
      if (mainteanceUsers.length < 1) {
        this.formItem.maintenanceUserName = ''
        this.formItem.maintenanceUserId = ''
      } else {
        this.formItem.maintenanceUserId = mainteanceUsers[0].username
        this.formItem.maintenanceUserName = mainteanceUsers[0].name ? mainteanceUsers[0].name : mainteanceUsers[0].username
      }
      this.mainteanceSelDialogFormVisible = false
    },
    selectMainteanceCancel() {
      this.mainteanceSelDialogFormVisible = false
    },
    /** 选择资产 */
    handleSelectAssets() {
      this.assetSelDialogFormVisible = true
    },
    selectAssetOk() {
      const assets = this.$refs.assets.selections
      const assetCodes = this.formItem.assets.map(a => a.code)
      const difference = assets.filter(t => {
        return !assetCodes.includes(t.code)
      })
      this.formItem.assets.push(...difference)
      this.assetSelDialogFormVisible = false
      console.log(assets)
    },
    selectAssetCancel() {
      this.assetSelDialogFormVisible = false
    },
    /** 删除某一项 */
    handleRemove() {
      if (this.removeData.length === 0) {
        return this.$message({
          showClose: true,
          message: '请选择一项资产',
          type: 'error'
        })
      }
      this.formItem.assets = this.formItem.assets.filter(t => {
        return !this.removeData.includes(t.code)
      })
    },
    tableSelection(sel) {
      this.removeData = sel.map(a => a.code)
    }
  }
}
</script>
